using Microsoft.AspNetCore.Mvc;
using PandaWebAPI.Models.ef;
using PandaWebAPI.Services;

namespace PandaWebAPI.Controllers;

/// <summary>
/// 购物车控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class ShoppingCartController : ControllerBase
{
    private readonly IShoppingCartService _shoppingCartService;

    public ShoppingCartController(IShoppingCartService shoppingCartService)
    {
        _shoppingCartService = shoppingCartService;
    }

    /// <summary>
    /// 获取所有购物车
    /// </summary>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<ShoppingCart>>> GetAll()
    {
        var shoppingCarts = await _shoppingCartService.GetAllAsync();
        return Ok(shoppingCarts);
    }

    /// <summary>
    /// 根据ID获取购物车
    /// </summary>
    [HttpGet("{id}")]
    public async Task<ActionResult<ShoppingCart>> GetById(Guid id)
    {
        var shoppingCart = await _shoppingCartService.GetByIdAsync(id);
        if (shoppingCart == null)
        {
            return NotFound();
        }
        return Ok(shoppingCart);
    }

    /// <summary>
    /// 根据用户ID获取购物车
    /// </summary>
    [HttpGet("user/{userId}")]
    public async Task<ActionResult<ShoppingCart>> GetByUserId(Guid userId)
    {
        var shoppingCart = await _shoppingCartService.GetByUserIdAsync(userId);
        if (shoppingCart == null)
        {
            return NotFound();
        }
        return Ok(shoppingCart);
    }

    /// <summary>
    /// 创建购物车
    /// </summary>
    [HttpPost]
    public async Task<ActionResult<ShoppingCart>> Create(ShoppingCart shoppingCart)
    {
        var createdCart = await _shoppingCartService.CreateAsync(shoppingCart);
        return CreatedAtAction(nameof(GetById), new { id = createdCart.CartId }, createdCart);
    }

    /// <summary>
    /// 更新购物车
    /// </summary>
    [HttpPut("{id}")]
    public async Task<IActionResult> Update(Guid id, ShoppingCart shoppingCart)
    {
        if (id != shoppingCart.CartId)
        {
            return BadRequest();
        }

        await _shoppingCartService.UpdateAsync(shoppingCart);
        return NoContent();
    }

    /// <summary>
    /// 删除购物车
    /// </summary>
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        await _shoppingCartService.DeleteAsync(id);
        return NoContent();
    }

    /// <summary>
    /// 清空购物车
    /// </summary>
    [HttpPost("{id}/clear")]
    public async Task<IActionResult> ClearCart(Guid id)
    {
        await _shoppingCartService.ClearCartAsync(id);
        return NoContent();
    }
} 